package com.example.springlog.controller;

import com.example.springlog.config.log.LoggerConfig;
import com.example.springlog.entity.DesensitiveRule;
import com.example.springlog.enums.SensitivePatternEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Description:
 * @Author: 刘超
 * @Date: 2023-04-27 10:03
 */
@RestController
@RequestMapping("/log")
public class LogController {
    Logger logger = LoggerFactory.getLogger(LogController.class);

    @Autowired
    LoggerConfig loggerConfig;

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String logTest(@RequestParam String s) {
        logger.info("loginfo {},tell={}", s, s);
        logger.info(s);
        return "success";
    }

    @RequestMapping(value = "/sensitive", method = RequestMethod.GET)
    public String sensitive() {
        if (loggerConfig.isDesensitive()) {
            loggerConfig.setDesensitive(false);
        } else {
            loggerConfig.setDesensitive(true);
        }
        return "sensitive logger at " + LocalDateTime.now();
    }

    @RequestMapping(value = "/level", method = RequestMethod.GET)
    public String modLevel(@RequestParam String level){
        // 不需要校验，Level.toLevel(),做了判定，如果错误设置为默认level
        loggerConfig.setLevel(level);
        logger.debug("update level logger at " + LocalDateTime.now());
        logger.info("update level logger at " + LocalDateTime.now());
        logger.warn("update level logger at " + LocalDateTime.now());
        logger.error("update level logger at " + LocalDateTime.now());
        return "update level logger at " + LocalDateTime.now();
    }

    @RequestMapping(value = "/rule", method = RequestMethod.GET)
    public String modRules(){
        List<DesensitiveRule> rules = new ArrayList<>();
        rules.add(new DesensitiveRule(SensitivePatternEnum.email.getRegex(), SensitivePatternEnum.email.getRule()));
        loggerConfig.setRules(rules);
        return "update rules logger at " + LocalDateTime.now();
    }

}
